package com.share.cloudStorage.shares.controller;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.share.cloudStorage.files.model.Files;
import com.share.cloudStorage.files.service.FilesService;
import com.share.cloudStorage.filter.SecurityFilter;
import com.share.cloudStorage.folders.model.Folders;
import com.share.cloudStorage.folders.service.FoldersService;
import com.share.cloudStorage.hdfs.HdfsClient;
import com.share.cloudStorage.model.Result;
import com.share.cloudStorage.shares.model.Shares;
import com.share.cloudStorage.shares.service.SharesService;
import com.share.cloudStorage.users.model.Users;
import com.share.cloudStorage.users.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Calendar.DAY_OF_MONTH;

@RestController
@RequestMapping("/api/v1/shares")
@Slf4j
/*
 * 自定义响应码
 * 411 代表该文件已有分享链接
 * 412 表示文件密码不对
 * 413 表示文件不见了
 * 414 表示文件来晚了，文件已删除
 * */
public class SharesController {

    @Autowired
    private SharesService sharesService;

    @Autowired
    private FilesService filesService;

    @Autowired
    private FoldersService foldersService;

    @Autowired
    private HdfsClient hdfsClient;

    //创建分享链接
    @PostMapping("create")
    public Result create(@RequestBody Shares shares) {
        //先判断该文件是否有链接
        QueryWrapper<Shares> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("file_id",shares.getFileId());
        queryWrapper.eq("status",0);
        int count = sharesService.count(queryWrapper);
        if (count > 0) {
            return Result.ok(411,"该文件已有分享链接",null);
        }

        shares.setUserId(SecurityFilter.userid.get());
        //使用uuid生成链接
        String link = IdUtil.randomUUID();
        shares.setShareLink(link);

        //判断密码是否有
        if (shares.getSharePassword() == null) {
            shares.setSharePassword("");
            shares.setIsPasswordProtected(1);
        }

        //根据时间有效期类型去设置链接有效期
        Calendar calendar = Calendar.getInstance();
        Integer validType = shares.getValidType();

        switch (validType) {
            case 0:
                calendar.add(Calendar.DATE, 1);
                break;
            case 1:
                calendar.add(Calendar.DATE, 7);
                break;
            case 2:
                calendar.add(Calendar.DATE, 30);
                break;
            case 3:
                calendar.set(Calendar.YEAR,2099);
                break;
                // 注意：这里没有break，因为对于case 3，也需要设置过期时间
            default:
                // 如果validType不是预期的值，可以在这里处理或者抛出异常
                throw new IllegalArgumentException("Invalid validType: " + validType);
        }
        shares.setExpirationTime(calendar.getTime());


        log.info("Create Shares : {}", shares);
        sharesService.save(shares);
        return Result.ok(shares);
    }

    //通过链接获取相关信息
    @GetMapping("getShareInfo")
    public Result getShareInfo(@RequestParam String link) {
        int count = sharesService.count(new QueryWrapper<Shares>().eq("share_link", link));
        if (!(count > 0)) {
            return Result.ok(413,"文件不见了",null);
        }
        return Result.ok(sharesService.getShareInfo(link));
    }
    //验证分享密码是否正确
    @PostMapping("checkShareCode")
    public Result checkShareCode(@RequestBody Shares shares) {
        QueryWrapper<Shares> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("share_id",shares.getShareId());
        queryWrapper.eq("share_password",shares.getSharePassword());
        int count = sharesService.count(queryWrapper);
        return count>0?Result.ok():Result.ok(412,"提取码有误",null);
    }

    //验证直接通过链接进入
    @GetMapping("checkShare/{link}")
    public Result checkShare(@PathVariable String link,@RequestParam("sharePassword") String sharePassword,@RequestParam("shareId") Integer shareId) {
        int count = sharesService.count(new QueryWrapper<Shares>().eq("share_link", link));
        if (!(count > 0)) {
            return Result.ok(413,"文件不见了",null);
        }
        QueryWrapper<Shares> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("share_id",shareId);
        queryWrapper.eq("share_password",sharePassword);
        queryWrapper.eq("share_link",link);
        int count2 = sharesService.count(queryWrapper);
        if (!(count2 > 0)) {
            return Result.ok(412,"提取码有误",null);
        }
        Shares shareInfo = sharesService.getShareInfo(link);
        shareInfo.setCurrentUser(shareInfo.getUserId().equals(SecurityFilter.userid.get()));
        return Result.ok(shareInfo);
    }

    //取消分享
    @GetMapping("cancelShare")
    public void cancelShare(@RequestParam("shareId") String shareIds) {
        UpdateWrapper<Shares> updateWrapper = new UpdateWrapper<>();
        String[] split= shareIds.split(",");
        List<Integer> shareIdList = Arrays.stream(split)
                .map(Integer::parseInt) // 将字符串转换为整数
                .collect(Collectors.toList());
        updateWrapper.in("share_id", shareIdList) // 使用整数列表作为条件
                .set("status", 1); // 设置需要更新的字段和值
        sharesService.update(updateWrapper);
    }
    //查询分享的文件
    @GetMapping("searchByFileId")
    public Result searchByFileId(@RequestParam Integer fileId) {
        List<Files> files = filesService.searchByFileId(fileId);
        return files.isEmpty()?Result.ok(414,"来晚了，文件已删除",null):Result.ok(files);
    }

    //根据用户id查询所有的分享
    @GetMapping("searchAllByUserId")
    public List<Shares> searchAllByUserId() {
        return sharesService.searchAllByUserId(SecurityFilter.userid.get());
    }

    //获取该用户当前所有目录
    @GetMapping("getAllFolderList")
    public List<Files> getAllFolderList(){
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_folder",1);
        queryWrapper.eq("user_id",SecurityFilter.userid.get());
        queryWrapper.eq("is_delete",0);
        queryWrapper.eq("is_recycle",0);
        return filesService.list(queryWrapper);
    }
    //保存到我的网盘
    @GetMapping("saveMyPan")
    @Transactional
    public void saveMyPan(@RequestParam("shareId") String shareId,@RequestParam("myFileId") Integer myFileId) throws IOException {
        String[] shareIds = shareId.split(",");
        ArrayList<Integer> shareIdList = new ArrayList<>();
        for (String id : shareIds) {
            shareIdList.add(Integer.parseInt(id));
        }
        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("file_id", shareIdList);
        List<Files> list = filesService.list(queryWrapper);
        saveShare(list,myFileId);

        //取获取所以分享人的文件路径和接受人的文件路径
        Files shareFile = filesService.getById(shareId);
        QueryWrapper<Folders> shareFileFoldersQueryWrapper = new QueryWrapper<>();
        shareFileFoldersQueryWrapper.eq("user_id",shareFile.getUserId());
        Folders shareFolders = foldersService.list(shareFileFoldersQueryWrapper).get(0);
        log.info(shareFile.toString());
        log.info(shareFolders.toString());

        Files acceptFile = filesService.getById(myFileId);
        QueryWrapper<Folders> acceeptFileFoldersQueryWrapper = new QueryWrapper<>();
        acceeptFileFoldersQueryWrapper.eq("user_id",SecurityFilter.userid.get());
        Folders acceptFolders = foldersService.list(acceeptFileFoldersQueryWrapper).get(0);
        log.info(acceptFile.toString());
        log.info(acceptFolders.toString());

        String sharePath = shareFolders.getFolderName() + "/"+ shareFile.getFilePath();
        String acceptPath = acceptFolders.getFolderName() + "/" +  acceptFile.getFilePath();
        hdfsClient.moveFile(sharePath,acceptPath);

        String filePath = shareFile.getFilePath();

    }
    //定义一个list集合用来存放分享到我的网盘的文件
    public void saveShare(List<Files> list,Integer myFileId){
        ArrayList<Files> filesList = new ArrayList<>();
        for (Files files : list) {
            QueryWrapper<Files> filesQueryWrapper = new QueryWrapper<>();
            filesQueryWrapper.eq("file_id", myFileId);
            Files file = filesService.getOne(filesQueryWrapper);
            files.setUserId(SecurityFilter.userid.get());
            files.setParentId(myFileId);
            files.setFilePath(file.getFilePath() + "/" +files.getFileName());
            if (!files.getIsFolder()){
                filesList.add(files);
            }else {
                QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("parent_id", files.getFileId());
                List<Files> childList = filesService.list(queryWrapper);
                filesService.save(files);
                saveShare(childList,files.getFileId());
            }
        }
        filesService.saveBatch(filesList);
    }
}

